const Router = require("koa-router");
const router = new Router({ prefix: "/user" });
const { response, generateToken } = require("../utils");

router.get("/getUsers", async (ctx) => {
  try {
    const rows = await new Promise((resolve, reject) => {
      ctx.db.all("SELECT * FROM users", [], (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });

    ctx.body = response(true, "Users fetched successfully", rows);
  } catch (err) {
    ctx.status = 500;
    ctx.body = response(false, "Failed to fetch users");
  }
});

router.post("/login", async (ctx) => {
  const { username, password } = ctx.request.body;
  try {
    const user = await new Promise((resolve, reject) => {
      ctx.db.get(
        "SELECT * FROM users WHERE username = ? AND password = ?",
        [username, password],
        (err, row) => {
          if (err) {
            reject(err);
          } else {
            resolve(row);
          }
        }
      );
    });

    if (user) {
      const token = generateToken({ username: user.username });
      ctx.body = response(true, "Login successful", { token });
    } else {
      ctx.status = 401;
      ctx.body = response(false, "Invalid username or password");
    }
  } catch (err) {
    ctx.status = 500;
    ctx.body = response(false, "Login failed due to server error");
  }
});

module.exports = router;
